import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

public class ConnectionReader extends Thread {
	private Connection connection;
	private Socket socket;
	private ObjectInputStream inStream; 
	private Serwer serwer;
	private Message m;
	
	public ConnectionReader(Connection c, Serwer s) {
		serwer = s;
		socket = c.socket;
		try {
		inStream = new ObjectInputStream(socket.getInputStream()); 
		} catch(Exception e) { System.out.println(e.getMessage()); }
	System.out.println("connection reader started");
	
	}
	
	protected Message getMessage() {
		Message m = null;
			//inStream.mark();
			//inStream.reset();
			try {
				m = (Message) inStream.readObject();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		 

		
		return m;
	}
	
	public void handleMessage(Message m) throws IOException {
		serwer.handleMessage(m);
	}
	
	public void run() {
		while(true) {
			System.out.println("waiting");
				Message m = getMessage();
				if(m == null)
				{
					System.out.println("Awaria polaczenia") ;
					serwer.zamknijPisarza() ;
					try {
						socket.close() ;
					} catch (IOException e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();
					}
					break ;
				}
				try {
					this.handleMessage(m);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}
}